﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

using JM.JCY.Proxy;
using JM.JCY.BusinessEntity;
using JM.JCY.Common;
using NCS.IConnect.ApplicationContexts;
using System.Data;
using System.Web;
using System.Collections.Generic;
using JM.JCY.Common.Utilities;

namespace JM.JCY.SharePointComponent.PhotoAlbum.ViewMedia
{
    public partial class ViewMediaUserControl : UserControl
    {
        public int _mediaId
        {
            get
            {
                return (int)ViewState["_mediaId"];
            }
            set
            {
                ViewState["_mediaId"] = value;
            }
        }

        public int _albumId
        {
            get
            {
                return (int)ViewState["_albumId"];
            }
            set
            {
                ViewState["_albumId"] = value;
            }
        }

        public string _userName
        {
            get
            {
                return (string)ViewState["_userName"];
            }
            set
            {
                ViewState["_userName"] = value;
            }
        }

        public int _staffId
        {
            get
            {
                return (int)ViewState["_staffId"];
            }
            set
            {
                ViewState["_staffId"] = value;
            }
        }

        public string appType
        {
            set;
            get;
        }
        public int appId
        {
            set;
            get;
        }

        private void LoadApplicationContext()
        {
            _staffId = 11;
            if (ApplicationContext.Current.GetKeyValue("userId") != null)
            {
                _staffId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("userId"));
            }

            if (ApplicationContext.Current.GetKeyValue("appType") != null)
            {
                appType = ApplicationContext.Current.GetKeyValue("appType").ToString();
            }

            switch (appType)
            {
                case JCYConstant.PhotoAlbum.ApplicationTypeName.PublicName:
                    appId = 0;
                    break;
                case JCYConstant.PhotoAlbum.ApplicationTypeName.PersonalName:
                    appId = _staffId;
                    break;
                case JCYConstant.PhotoAlbum.ApplicationTypeName.WorkgroupName:
                    if (ApplicationContext.Current.GetKeyValue("AppId") != null)
                    {
                        appId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("AppId"));
                    }
                    break;
                case JCYConstant.PhotoAlbum.ApplicationTypeName.CommitteeName:
                    if (ApplicationContext.Current.GetKeyValue("AppId") != null)
                    {
                        appId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("AppId"));
                    }
                    break;
            }
        }

        public string CreatedBy
        {
            set { Session["ocp_album_createdBy"] = value; }
            get
            {
                if (Session["ocp_album_createdBy"] == null)
                {
                    return string.Empty;
                }
                else
                {
                    return Session["ocp_album_createdBy"].ToString();
                }
            }
        }

        public bool removed
        {
            set;
            get;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string removeMedia = Request.Params.Get("__EVENTTARGET");
            LoadApplicationContext();

            if (!IsPostBack)
            {
                if (Request.QueryString["MediaId"] != null && Request.QueryString["AlbumId"] != null)
                {
                    _mediaId = Int32.Parse(Request.QueryString["MediaId"].ToString());
                    _albumId = Int32.Parse(Request.QueryString["AlbumId"].ToString());

                    this.HiddenStaffId.Value = _staffId.ToString();
                    this.HiddenMediaId.Value = _mediaId.ToString();
                    this.HiddenAlbumId.Value = _albumId.ToString();
                    this.HiddenUserName.Value = SPContext.Current.Web.CurrentUser.LoginName;
                    LoadMedia(_mediaId);
                }

              PhotoAlbumDataSet _albumDs = null;

              using (PhotoAlbumProxy accessProxy = new PhotoAlbumProxy())
              {
                  _albumDs = accessProxy.getAlbumDbyAlbumId(Convert.ToInt32(_albumId));
                  int createdBy = _albumDs.T_Album[0].Creator;
                  CreatedBy = createdBy.ToString();
                  //type is public
                  if (appType.Equals(JCYConstant.PhotoAlbum.ApplicationTypeName.PublicName) || appType.Equals(JCYConstant.PhotoAlbum.ApplicationTypeName.PersonalName))
                  {
                      //current web is in mysite.
                      if (_staffId.Equals(_albumDs.T_Album[0].Creator))
                      {
                          HiddenFieldEableEdit.Value = "T";//true.
                      }
                      else
                      {
                          HiddenFieldEableEdit.Value = "F";//False.
                      }
                  }
                  else if (appType.Equals(JCYConstant.PhotoAlbum.ApplicationTypeName.WorkgroupName))
                  {
                      //the album is in workgroup
                      PhotoAlbumSearchDataSet.T_UserDepartmentDataTable department = accessProxy.GetAllDepartmentUsersById(appId);
                      DataRow[] rows = department.Select(string.Format("UserId={0}", _staffId));

                      if (rows.Length > 0)
                      {
                          HiddenFieldEableEdit.Value = "T";
                      }
                      else
                      {
                          HiddenFieldEableEdit.Value = "F";
                      }

                  }
                  else if (appType.Equals(JCYConstant.PhotoAlbum.ApplicationTypeName.CommitteeName))
                  {
                      //the album is in committe
                      PhotoAlbumSearchDataSet.T_UserCommitteeDataTable committee = accessProxy.GetAllCommitteeUsersById(appId);

                      DataRow[] rows = committee.Select(string.Format("UserId={0}", _staffId));

                      if (rows.Length > 0)
                      {
                          HiddenFieldEableEdit.Value = "T";
                      }
                      else
                      {
                          HiddenFieldEableEdit.Value = "F";
                      }
                  }
              }
            }
            if (removeMedia != null && removeMedia.IndexOf("AlbumRemoveThisMedia") > -1)
            {

                ButtonRemoveMedia(Convert.ToInt32(HiddenUpdateMediaId.Value));
            }

        }

        private void LoadMedia(int albumId)
        {
            HiddenDisable.Value = "false";
           PhotoAlbumSearchDataSet.T_AlbumContentDataTable AlbumContentDT;
           using (PhotoAlbumProxy proxy = new PhotoAlbumProxy())
            {
                //get media data
                AlbumContentDT = proxy.GetMadieById(_mediaId);
                var mediaRow = AlbumContentDT[0];
                if (AlbumContentDT.Rows.Count > 0)
                {
                    string ImageName = mediaRow.OriginalImgUrl.ToString().Substring(mediaRow.OriginalImgUrl.LastIndexOf("/") + 1);
                    string picName = ImageName.ToString().Substring(0, ImageName.LastIndexOf("."));
                    if (mediaRow.Description != "")
                        this.HiddenDesc.Value = mediaRow.Description;
                    else
                        this.HiddenDesc.Value = "";
                    //this.RedictUrl.HRef = mediaRow.OriginalImgUrl;
                    this.HiddenImgOriginalUrl.Value = mediaRow.OriginalImgUrl;
                    this.HiddenImgFullName.Value = ImageName;
                    this.HiddenPicName.Value = picName;
                }
                //get album data
                AlbumContentDT = proxy.GetMadieByAlbumId(_albumId);
                if (AlbumContentDT.Rows.Count > 0)
                {
                    HiddenFieldAlumName.Value = AlbumContentDT[0].AlbumName;
                    string query = "";
                    string idnamesQuery = string.Empty;
                    for (int i = 0; i < AlbumContentDT.Rows.Count; i++)
                    {

                        string picFullName = AlbumContentDT[i]["OriginalImgUrl"].ToString().Substring(AlbumContentDT[i]["OriginalImgUrl"].ToString().LastIndexOf("/") + 1);
                        if (i != AlbumContentDT.Rows.Count - 1)
                        {
                            query += "[" + "'" + AlbumContentDT[i]["OptimizeImgUrl"].ToString() + "','" + AlbumContentDT[i].Description + "','" + AlbumContentDT[i]["OriginalImgUrl"].ToString() + "','" + picFullName + "','" + AlbumContentDT[i]["AlbumContentId"].ToString() + "','" + AlbumContentDT[i]["SharePointObjectId"].ToString() + "'],";
                            idnamesQuery += "[" + "'" + AlbumContentDT[i]["StaffId"].ToString() + "','" + AlbumContentDT[i]["CREATED_BY"].ToString() + "','" + AlbumContentDT[i]["ThumbNailImgUrl"].ToString() + "'],";
                        }
                        else
                        {
                            query += "[" + "'" + AlbumContentDT[i]["OptimizeImgUrl"].ToString() + "','" + AlbumContentDT[i].Description + "','" + AlbumContentDT[i]["OriginalImgUrl"].ToString() + "','" + picFullName + "','" + AlbumContentDT[i]["AlbumContentId"].ToString() + "','" + AlbumContentDT[i]["SharePointObjectId"].ToString() + "']";
                            idnamesQuery += "[" + "'" + AlbumContentDT[i]["StaffId"].ToString() + "','" + AlbumContentDT[i]["CREATED_BY"].ToString() + "','" + AlbumContentDT[i]["ThumbNailImgUrl"].ToString() + "']";
                        }

                    }

                    query = "[" + query + "]";
                    idnamesQuery = "[" + idnamesQuery + "]";
                    this.llArrows.Text = query;
                    this.lidnames.Text = idnamesQuery;
                    if (AlbumContentDT.Rows.Count == 1)
                    {
                        HiddenDisable.Value = "true";
                    }
                }
            }
        }

        protected void lbDownload_Click(object sender, EventArgs e)
        {
            OpenAttachment(this.HiddenImgOriginalUrl.Value.ToString(), this.HiddenImgFullName.Value.ToString());
        }

        public void OpenAttachment(string url, string picName)
        {
            try
            {
                //set the content type of file according to extension
                string[] fext = picName.Split('.');

                // Get the extension of File to determine the file type
                string casestring = "";
                if (fext.Length > 1)
                {
                    casestring = fext[fext.Length - 1];
                }

                SPWeb web = SPContext.Current.Web;
                web.AllowUnsafeUpdates = true;
                string contentType = "";

                SPFile tempFile = web.GetFile(url);

                byte[] obj = (byte[])tempFile.OpenBinary();
                switch (casestring)
                {

                    case "jpg": contentType = "image/jpeg";

                        break;

                    case "jpeg": contentType = "image/jpeg";

                        break;

                    case "gif": contentType = "image/gif";

                        break;

                    case "bmp": contentType = "image/bmp";

                        break;

                    case "png": contentType = "image/x-png";

                        break;

                    case "tif": contentType = "image/tiff";

                        break;

                    case "flv": contentType = "video/x-flv";

                        break;
                }

                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename= " + picName);
                HttpContext.Current.Response.ContentType = contentType;

                //Check that the client is connected and has not closed the connection after the request

                if (HttpContext.Current.Response.IsClientConnected)
                    HttpContext.Current.Response.BinaryWrite(obj);

                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.Close();

                web.AllowUnsafeUpdates = false;
            }

            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

        public void ButtonRemoveMedia(int currentMediaId)
        {
            bool deleteAlbum = false;
            string gotoUrl = string.Empty;
            try
            {
                string siteName = string.Empty;
                switch (SPContext.Current.Web.ServerRelativeUrl.ToLower())
                {
                    case "/":
                        siteName = string.Empty;
                        break;
                    case "/mysite":
                        siteName = JCYConstant.SiteUrlName.MySite;
                        break;
                    case "/mydept":
                        siteName = JCYConstant.SiteUrlName.MyDept;
                        break;
                    case "/mycommittee":
                        siteName = JCYConstant.SiteUrlName.MyCommittee;
                        break;
                }

                using (PhotoAlbumProxy funProxy = new PhotoAlbumProxy())
                {
                    PhotoAlbumDataSet funds = funProxy.getAlbumDbyAlbumId(_albumId);
                    if (funds.T_Album.Rows.Count == 1)
                    {
                        SPInputs input = new SPInputs();
                        PhotoAlbumDataSet.T_AlbumContentRow albumContent = funds.T_AlbumContent.FindByAlbumContentId(currentMediaId);
                        PhotoAlbumDataSet.T_SharePointObjectRow spObject = funds.T_SharePointObject.FindBySharePointObjectId(albumContent.SharePointObjectId);

                        input.SiteName = siteName;
                        input.SPFolderID = funds.T_SharePointObject[0].SPFolderId;
                        input.SPListItemID = spObject.SPListItemId;

                        SPOutputs outs = JCYSharePointHelper.RemoveMedia(input);
                        if (outs.IsError == false)
                        {
                            if (funds.T_AlbumContent.Rows.Count == 1)
                            {
                                deleteAlbum = true;
                                foreach (PhotoAlbumDataSet.T_SharePointObjectRow objRow in funds.T_SharePointObject.Rows)
                                {
                                    objRow.IsDeleted = true;
                                    objRow.LAST_UPDATED_BY = SPContext.Current.Web.CurrentUser.Name;
                                    objRow.LAST_UPDATED_TIME = DateTime.Now;
                                }

                                foreach (PhotoAlbumDataSet.T_AlbumRow albumRow in funds.T_Album.Rows)
                                {
                                    albumRow.IsDeleted = true;
                                    albumRow.LatestUpdateTime = DateTime.Now;
                                    albumRow.LAST_UPDATED_TIME = DateTime.Now;
                                    albumRow.LAST_UPDATED_BY = SPContext.Current.Web.CurrentUser.Name;
                                }

                                foreach (PhotoAlbumDataSet.T_AlbumContentRow contentRow in funds.T_AlbumContent.Rows)
                                {
                                    contentRow.IsDeleted = true;
                                    contentRow.LAST_UPDATED_BY = SPContext.Current.Web.CurrentUser.Name;
                                    contentRow.LAST_UPDATED_TIME = DateTime.Now;
                                }

                            }
                            else
                            {
                                spObject.IsDeleted = true;
                                spObject.LAST_UPDATED_TIME = DateTime.Now;
                                spObject.LAST_UPDATED_BY = _userName;

                                albumContent.IsDeleted = true;
                                albumContent.LAST_UPDATED_BY = _userName;
                                albumContent.LAST_UPDATED_TIME = DateTime.Now;
                                albumContent.StaffId = _staffId;

                                if (albumContent.ThumbNailImgUrl.Equals(funds.T_Album[0].ThumbNailImgUrl))
                                {
                                    funds.T_Album[0].ThumbNailImgUrl = funds.T_AlbumContent[1].ThumbNailImgUrl;
                                }
                                funds.T_Album[0].ItemCount = funds.T_Album[0].ItemCount - 1;
                            }
                        }
                        else
                        {
                            //showMessage(outs.Message.Replace("\r\n", ""));
                            Exception ex = new Exception(outs.Message.Replace("\r\n", ""));
                            bool isok = JCYUtility.ExceptionHandle("sharepoint list remove Media", ex);
                            if (isok == false)
                            {
                                throw ex;
                            }
                            return;
                        }

                        funProxy.CreateAlbumwithUpload(funds);
                        if (deleteAlbum)
                        {
                            gotoUrl = "ViewAllAlbums.aspx";
                        }
                        else
                        {   
                            //update feedpost postcontent
                            gotoUrl = string.Format("ViewAlbum.aspx?AlbumId={0}", _albumId);
                        }
                    }
                }
                Response.Redirect(gotoUrl);
            }
            catch (Exception ex)
            {
                bool isok = JCYUtility.ExceptionHandle("remove Media", ex);
                if (isok == false)
                {
                    throw ex;
                }
                return;
            }
        }
    }
}
